package pcgen.android;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Utils 
{
    public static String fromStreamToString(InputStream input) throws Throwable
    {
        try
		{
        	BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            
            try
            {
            	reader = new BufferedReader(new InputStreamReader(input));
    	
    	        String line = null;
    	        while ((line = reader.readLine()) != null) 
    	            sb.append(line + "\n");
            }
            finally
            {
				try
				{
					if (reader != null)
	            		reader.close();
				}
				catch (Exception ex) {}
				
            	try
				{
					if (input != null)
						input.close();
				}
				catch (Exception ex) {}
            }
            
            return sb.toString();
		}
		catch (Throwable tr)
		{
			Logger.e(TAG, "fromStream", tr);
			throw tr;
		}
    }
    
    static final char[] DIGITS = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String toHex(byte[] bytes) 
    {
    	char[] out = new char[bytes.length * 2]; // 2  hex characters per byte
    	for (int i = 0; i < bytes.length; i++) 
    	{
    		out[2*i] = DIGITS[bytes[i] < 0 ? 8 + (bytes[i] + 128) / 16 : bytes[i] / 16]; // append sign bit for negative bytes
    		out[2*i + 1] = DIGITS[bytes[i] < 0 ? (bytes[i] + 128) % 16 : bytes[i] % 16];
    	}
      
    	return new String(out); // char sequence to string
    }
    
    private static final String TAG = Utils.class.getSimpleName();
}
